using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;
using System.Xml.Serialization;
using System.IO;
using System.Text;

namespace ASPXPages
{
    public partial class Association : Page
    {
        protected SPList List;
        protected SPContentType m_ct;
        protected string m_workflowName;
        protected bool m_allowManual;
        protected bool m_autoStartCreate;
        protected bool m_autoStartChange;
        protected Guid m_taskListId;
        protected string m_taskListName;
        protected Guid m_historyListId;
        protected string m_historyListName;
        protected bool m_setDefault;
        protected bool m_updateLists;
        protected bool m_bLockItem;
        protected SPWorkflowTemplate m_baseTemplate;
        protected SPWorkflowAssociation m_assocTemplate;
        protected bool m_bContentTypeTemplate = false;
        
        //protected SPWeb Web;

        protected void Page_Load(object sender, EventArgs e)
        {
            txtUrl.Text = Request.Url.ToString();
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            if (txtList.Text != "")
            {               
                SPList emailList = SPContext.Current.Web.Lists[txtList.Text];

                if (emailList != null)
                {
                    foreach (SPField field in emailList.Fields)
                    {
                        if (field.TypeAsString == "User")
                            lbPersons.Items.Add(new ListItem(field.Title));
                    }
                }
            }
        }

        protected override void OnLoad(EventArgs ea)
        {
            base.OnLoad(ea);
            m_workflowName = Request.Params["WorkflowName"];

            EnsureRequestParamsParsed();
            FetchAssociationInfo();
            
            GetTaskAndHistoryList();
        }

        string m_strQueryParams = "";
        protected void EnsureRequestParamsParsed()
        {
            string strListID = Request.QueryString["List"];
            
            if (strListID != null)
                List = SPContext.Current.Web.Lists[new Guid(strListID)];           
                m_strQueryParams = "?List=" + strListID;
        }
        #region Fetch Methods

        private void FetchAssociationInfo()
        {
            SPWorkflowAssociationCollection wac;
            m_baseTemplate = SPContext.Current.Web.WorkflowTemplates[new Guid(Request.Params["WorkflowDefinition"])];
            m_assocTemplate = null;

            //List.Permissions.CheckPermissions(SPRights.ManageListPermissions);
            wac = List.WorkflowAssociations;
            hlReturn.Text = List.Title;
            hlReturn.NavigateUrl = List.DefaultViewUrl;
           
            if (wac == null || wac.Count < 0)
            {
                throw new SPException("No Associations Found");
            }
            //Set the general workflow properties
            m_autoStartCreate = (Request.Params["AutoStartCreate"] == "ON");
            m_autoStartChange = (Request.Params["AutoStartChange"] == "ON");
            m_allowManual = (Request.Params["AllowManual"] == "ON");
            m_bLockItem = (Request.Params["LockItem"] == "ON");
            m_setDefault = (Request.Params["SetDefault"] == "ON");
            m_updateLists = (Request.Params["UpdateLists"] == "TRUE");
            // check if workflow association already exists.
            string strGuidAssoc = Request.Params["GuidAssoc"];
            if (strGuidAssoc != string.Empty)
            {
                m_assocTemplate = wac[new Guid(strGuidAssoc)];
            }

            // Check for a duplicate name. Note that we do this both on initial load and on
            // postback. The reason we do it on postback is that some other user may have
            // added a workflow by this name since the last time we checked.
            SPWorkflowAssociation dupTemplate = wac.GetAssociationByName(m_workflowName, SPContext.Current.Web.Locale);
            if (dupTemplate != null && (m_assocTemplate == null || m_assocTemplate.Id != dupTemplate.Id))
            {
                // throw an exception if there is a template with the same name already
                throw new SPException("Duplicate workflow name is detected.");
            }
        }

        private void GetTaskAndHistoryList()
        {
            if (m_bContentTypeTemplate)
            {
                m_taskListName = Request.Params["TaskList"];
                m_historyListName = Request.Params["HistoryList"];
            }
            else
            {

                // If the user has requested that a new task or history list be created, check
                // that the name does not duplicate the name of an existing list. If it does, show
                // the user an appropriate error page.

                string taskListGuid = Request.Params["TaskList"];
                if (taskListGuid[0] != 'z') // already existing list
                {
                    m_taskListId = new Guid(taskListGuid);
                }
                else  // new list
                {
                    SPList list = null;
                    m_taskListName = taskListGuid.Substring(1);
                    try
                    {
                        list = SPContext.Current.Web.Lists[m_taskListName];
                    }
                    catch (ArgumentException)
                    {
                    }

                    if (list != null)
                        throw new SPException("A list already exists with the same name as that proposed for the new task list. Use your browser's Back button and either change the name of the workflow or select an existing task list.&lt;br&gt;");
                }

                // do the same for the history list
                string strHistoryListGuid = Request.Params["HistoryList"];
                if (strHistoryListGuid[0] != 'z') // user selected already existing list
                {
                    m_historyListId = new Guid(strHistoryListGuid);
                }
                else // user wanted a new list
                {
                    SPList list = null;

                    m_historyListName = strHistoryListGuid.Substring(1);

                    try
                    {
                        list = SPContext.Current.Web.Lists[m_historyListName];
                    }
                    catch (ArgumentException)
                    {
                    }
                    if (list != null)
                        throw new SPException("A list already exists with the same name as that proposed for the new history list. Use your browser's Back button and either change the name of the workflow or select an existing history list.&lt;br&gt;");
                }
            }
        }
        #endregion


        protected void btnOk_Click(object sender, EventArgs e)
        {
            SPList taskList = null;
            SPList historyList = null;
            if (!IsValid)
                return;
           
            // If the user requested a new task list, create it.
            if (m_taskListId == Guid.Empty)
            {
                string description = string.Format("Task list for the {0} workflow.", m_workflowName);
                m_taskListId = SPContext.Current.Web.Lists.Add(m_taskListName, description, SPListTemplateType.Tasks);
            }

            // If the user requested a new history list, create it.
            if (m_historyListId == Guid.Empty)
            {
                string description = string.Format("History list for the {0} workflow.", m_workflowName);
                m_historyListId = SPContext.Current.Web.Lists.Add(m_historyListName, description, SPListTemplateType.WorkflowHistory);
            }
            taskList = SPContext.Current.Web.Lists[m_taskListId];
            historyList = SPContext.Current.Web.Lists[m_historyListId];
        

            // perform association (if it doesn't already exist)
            bool isNewAssociation;
            if (m_assocTemplate == null)
            {
                isNewAssociation = true;
                m_assocTemplate = SPWorkflowAssociation.CreateListAssociation(m_baseTemplate,
                                                  m_workflowName,
                                                  taskList,
                                                  historyList);
            }
            else // modify existing template
            {
                isNewAssociation = false;
                m_assocTemplate.Name = m_workflowName;
                m_assocTemplate.SetTaskList(taskList);
                m_assocTemplate.SetHistoryList(historyList);
            }

            // set up starup parameters in the template
            m_assocTemplate.Name = m_workflowName;
            m_assocTemplate.LockItem = m_bLockItem;
            m_assocTemplate.AutoStartCreate = m_autoStartCreate;
            m_assocTemplate.AutoStartChange = m_autoStartChange;
            m_assocTemplate.AllowManual = m_allowManual;

            if (m_assocTemplate.AllowManual)
            {
                SPBasePermissions newPerms = SPBasePermissions.EmptyMask;

                if (Request.Params["ManualPermEditItemRequired"] == "ON")
                    newPerms |= SPBasePermissions.EditListItems;
                if (Request.Params["ManualPermManageListRequired"] == "ON")
                    newPerms |= SPBasePermissions.ManageLists;

                m_assocTemplate.PermissionsManual = newPerms;
            }

            // place data from form into the association template
            m_assocTemplate.AssociationData = "<root><urlweb>" + txtUrl.Text.Substring(0, txtUrl.Text.IndexOf("_layouts"));
            m_assocTemplate.AssociationData += "</urlweb><persoonkolom>" + lbPersons.SelectedItem.Text;
            m_assocTemplate.AssociationData += "</persoonkolom><listnaam>" + txtList.Text + "</listnaam></root>";



            if (isNewAssociation) //if new association
                List.AddWorkflowAssociation(m_assocTemplate);
            else
                List.UpdateWorkflowAssociation(m_assocTemplate);

            if (m_assocTemplate.AllowManual && List.EnableMinorVersions)
            {
                //In case you selected this WF to be the content approval WF (m_setDefault = true see association page)
                if (List.DefaultContentApprovalWorkflowId != m_assocTemplate.Id && m_setDefault)
                {
                    if (!List.EnableModeration)
                        List.EnableModeration = true;
                    List.DefaultContentApprovalWorkflowId = m_assocTemplate.Id;
                    List.Update();
                }
                else if (List.DefaultContentApprovalWorkflowId == m_assocTemplate.Id && !m_setDefault)
                {
                    // Reset the DefaultContentApprovalWorkflowId
                    List.DefaultContentApprovalWorkflowId = Guid.Empty;
                    List.Update();
                }
            }

            string strUrl = List.DefaultViewUrl;
            Response.Redirect(strUrl);
        }
    }
}
